import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import weui from 'weui.js';
import weixinShare from '../../lib/weixinShare';
import { addErrorListener } from '../../lib/handleError';
import Banner from "../../components/Slide/index";

import AJAX from '../../lib/ajax';

const Dialog = require('../MyPackage/components/Dialog')

require('../../lib/rem');
require('../../styles/common.less');
require('./CouponsTask.less');
require('../../styles/iconfont/iconfont.css');

class CouponsTaskElem extends Component {
    constructor(props) {
        super(props)

        this.state = {
            isReady: false,     //是否可以加载页面
            userInfo: {},
            taskInfo: {},
            taskId: '',
            pictureInfo: {
                index: 0,
                list: [
                    {
                        id: 1,
                        link: '',
                        title: '',
                        src: '',
                    },
                    {
                        id: 2,
                        link: '',
                        title: '',
                        src: '',
                    },
                ]
            },
            banner_data: [
                {
                    link: '',
                    title: '轮播',
                    id: 1,
                    src: '',
                }
            ],//广告图
        };
    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll()
    }

    componentDidMount() {
        AJAX.request("user_home", {}, (data) => {
            if (data.code === 0) {
                const { href } = window.location;
                const taskId = href.split('?taskId=')[1];
                this.setState({
                    userInfo: data.body,
                    taskId,
                }, () => this.fetchCouponsInfo());
            }
        }, './Coupons');
    }

    fetchCouponsInfo = () => {
        const { userInfo = {}, taskId: task_id } = this.state;
        const { id, phone, unionid } = userInfo;
        if (id && phone && unionid && task_id) {
            const loading = weui.loading('加载中');
            AJAX.request("task_detail", { task_id }, (data) => {
                if (data.code === 0) {
                    this.setState({
                        taskInfo: data.body,
                        isReady: true,
                    });
                }
            }, './Coupons');
            loading.hide();
        } else window.location.href = './Coupons';
    }

    /** 报名任务 */
    handleSignUpTask = () => {
        const { taskInfo } = this.state;
        if (taskInfo.userTaskStatus !== 1 && taskInfo.userTaskStatus !== 2) {
            this.refs.modalCover.style.display = 'flex';
        }
    }

    /** 确定报名 */
    handleConfirmSignUp = () => {
        const { taskId: task_id, userInfo } = this.state;
        const { uid, phone } = userInfo;
        const params = {
            phone,
            task_id
        };
        AJAX.request("task_apply", params, (data) => {
            if (data.code === 0) {
                weui.toast('已成功报名');
                this.goUpBack();
                this.fetchCouponsInfo();
                this.handleCloseModal();
            }
        }, './Coupons');
    }

    /** 关闭modal */
    handleCloseModal = () => {
        this.refs.modalCover.style.display = 'none';
    }

    goUpBack = () => {
        const coupons_main = this.refs.coupons_main;
        coupons_main.scrollTo(0, 0);
    }

    /** 展示图片 */
    handleShowPicture = (record, index) => {
        this.setState({
            pictureInfo: {
                index,
                // list: [ record.imgA, record.imgB ],
                list: [
                    {
                        id: 1,
                        link: '',
                        title: '',
                        src: record.imgA,
                    },
                    {
                        id: 2,
                        link: '',
                        title: '',
                        src: record.imgB,
                    },
                ]
            }
        }, () => {
            const { picture } = this.refs;
            picture.style.display = 'flex';
        });
    }

    /** 隐藏图片 */
    handleHidePicture = () => {
        const { picture } = this.refs;
        picture.style.display = 'none';
    }

    /** 切换展示的图片 */
    handleChangePicture = (type) => {
        const { pictureInfo } = this.state;
        let { index, list } = pictureInfo;
        if (type === 'prev' && index > 0) {
            index -= 1;
        } else if (type === 'next' && index < list.length - 1) {
            index += 1;
        }
        this.setState({
            pictureInfo: {
                ...pictureInfo,
                index,
            }
        })
    }

    handleStatAd(id, title, url) {
        // 新增广告统计
        AJAX.request('advertSave', {advertId: aditem_id, type: 2}, (data) => {
            const { code, body } = data;
            if (code === 0) {
                console.log('记录成功', body);
            }
        });
        AJAX.request("stat_advert", { advert_id: id, action: 1 }, (data) => {
            if (url) {
                if (url.indexOf("http") === 0) {
                    window.location.href = url
                } else {
                    window.location.href = "//" + url
                }
            }
        });
        if (window._hmt) {
            var _hmt = window._hmt;
            _hmt.push(["_trackEvent", "page", "click", id, title]);
        } else {
            AJAX.appendBaiduAnalysis(() => {
                var _hmt = window._hmt;
                _hmt.push(["_trackEvent", "page", "click", id, title]);
            });
        }
    }

    render() {
        const { taskInfo, pictureInfo, banner_data } = this.state;
        const { taskStepList = [] } = taskInfo;

        const { index, list } = pictureInfo;

        return (
            this.state.isReady &&
            <div className="couponsTask">
                <div className="coupons_header">
                    <span
                        className="icon iconfont iconIcon_left"
                        onClick={() => location.href = './Coupons'}
                    >
                        返回
                    </span>
                    <label className="header_title">任务详情</label>
                </div>
                <div className="coupons_main" ref="coupons_main">
                    <div className="main_back" />
                    <div className="task_content">
                        <div className="content_info">
                            <div className="info_title">
                                <img src={taskInfo.icon} alt={taskInfo.name} />
                                <label>{taskInfo.name}</label>
                            </div>
                            <div className="info_reward">奖励:{taskInfo.coupon / 100 || 0}元寄件券</div>
                        </div>
                        <div className="info_other">
                            <span>截止日期：{taskInfo.endTime}</span>
                            <span>审核平均时长：{taskInfo.verifyTime}{taskInfo.verifyUnit === 1 ? '小时' : '天'}</span>
                            <span>重复执行：{taskInfo.repeated ? '是' : '否'}</span>
                            <span>剩余次数：{taskInfo.remainCount}次</span>
                        </div>
                    </div>
                    <div className="task_steps">
                        <div className="steps_title">
                            <span className="title_icons">
                                <img src="https://cdn2.jinlb.cn/pic/dd/5d/dd5de96f9a3cef74d4545a52217a1485.png" alt="" />
                            </span>
                            <label className="title_label">任务步骤</label>
                            <span className="title_vice">(请参照以下任务步骤完成任务)</span>
                        </div>
                        <div className="steps_content">
                            {taskStepList.length ? taskStepList.map((item) => (
                                <div className="steps_box">
                                    <div className="item_box">
                                        <span className="item_num">{item.sort}</span>
                                        <p>{item.info}</p>
                                        <span className="steps_line steps_line_top" />
                                    </div>
                                    <div className="item_sample">
                                        {item.type === 1 ? (
                                            <div className="sample_box">
                                                <img onClick={() => this.handleShowPicture(item, 0)} src={item.imgA} />
                                                <img onClick={() => this.handleShowPicture(item, 1)} src={item.imgB} />
                                            </div>
                                        ) : (item.type === 2 ? (
                                            <div className="sample_box">
                                                {taskInfo.userTaskStatus === 1 && <a href={item.url}><input value={item.url} ref="sampleLink" readOnly className="sample_link" /></a>}
                                                {taskInfo.userTaskStatus === 1 && <button><a href={item.url}>点击开始</a></button>}
                                            </div>
                                        ) : <div className="sample_box" />)}
                                        <span className="steps_line" />
                                    </div>
                                </div>
                            )) : null}
                        </div>
                    </div>
                </div>
                <div className="myTaskBtn_box">
                    <button
                        className="myTaskBtn"
                        onClick={this.handleSignUpTask}
                    >
                        {taskInfo.userTaskStatus === 1 ? '进行中' : (taskInfo.userTaskStatus === 2 ? '已完成' : '报名任务')}
                    </button>
                </div>

                <div className="modal_cover" ref="modalCover">
                    <div className="signUp_modal">
                        <div className="modal_content">
                            <img src="https://cdn2.jinlb.cn/pic/d6/a9/d6a95061f3aea0d5bf5f074b98a250bc.png" alt="" />
                            <label className="modal_title">提示</label>
                            <p className="modal_tips">确定开始任务？请在一小时内完成</p>
                        </div>
                        <div className="signUp_oper">
                            <span
                                className="oper_cancel"
                                onClick={this.handleCloseModal}
                            >取消</span>
                            <span className="line" />
                            <span
                                className="oper_confirm"
                                onClick={this.handleConfirmSignUp}
                            >确定
                            </span>
                        </div>
                    </div>
                </div>
                <div className="picture mask" ref="picture" onClick={this.handleHidePicture}>
                    {/* <span
            className="icon iconfont iconguanbi"
            onClick={this.handleHidePicture}
          /> */}
                    {/* <div className="picture_oper">
            <span
              className={`icon iconfont iconIcon_left prev ${index <= 0 && 'active'}`}
              onClick={() => this.handleChangePicture('prev')}
            />
            <span
              className={`icon iconfont iconIcon_right next ${index >= list.length - 1 && 'active'}`}
              onClick={() => this.handleChangePicture('next')}
            />
          </div> */}
                    <Banner
                        handleStatAd={this.handleStatAd}
                        opts={list}
                        autoSlide={1}
                        continuous={1}
                    />
                    {/* <img src={list[index]} alt="" onClick={this.handleHidePicture} /> */}
                </div>
            </div>
        );
    }
}
ReactDOM.render(<CouponsTaskElem />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}
